package com.weepal.pavement.mqtt.demo.message;

import com.weepal.pavement.mqtt.demo.ThreadPool.DefaultPool;
import com.weepal.pavement.mqtt.demo.job.MqttDevicesMap;
import com.weepal.pavement.mqtt.demo.analysis.Analysiser;
import com.weepal.pavement.mqtt.demo.vo.MqttDevices;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MqttReceiver {
    @Autowired
    private Analysiser analysiser;

    @Bean
    @ServiceActivator(inputChannel = "defatuleMqttInputChannel")
    public MessageHandler handler() {
        return message -> haveMessage(message);
    }

    public void haveMessage(Message<?> message) {
        try {
            if (message.getPayload() instanceof byte[]) {
                String subTopic = message.getHeaders().get("mqtt_receivedTopic").toString();
                MqttDevices devicd = MqttDevicesMap.getDevicd(subTopic);
                DefaultPool.threadPoolExecutor.submit(new Thread(() -> {
                    Analysiser.devicesThreadLocal.set(devicd);
                    analysiser.deal(new String((byte[]) message.getPayload()));
                }));
            } else if ((message.getPayload() instanceof String)) {
                log.info("String :" + message.getHeaders().get("mqtt_topic") + ", " + message.getPayload());
            } else {
                log.info("other: " + message.getHeaders().get("mqtt_topic") + ", " + message.getPayload());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
